<template>
  <div>
    <a-upload
      v-model:file-list="fileList"
      name="file"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="false"
      :action="action"
      :before-upload="beforeUpload"
      @change="handleChange"
    >
      <img class="imgStyle" v-if="imagePath" :src="imagePath" alt="file" />
      <div v-else>
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import { ref } from 'vue'
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue'

const props = defineProps(['action'])
const imagePath: any = defineModel()
const emit = defineEmits(['submitImg'])

const imageUrl = ref('')
const fileList = ref([])
const loading = ref()

function getBase64(img: any, callback: any) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

const handleChange = (info: any) => {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    getBase64(info.file.originFileObj, (base64Url: string) => {
      imageUrl.value = info.file.response
      emit('submitImg', imageUrl)
      imagePath.value = base64Url
      loading.value = false
    })
  }
  if (info.file.status === 'error') {
    loading.value = false
    message.error('上传失败')
  }
}

const beforeUpload = (file: any) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('请传入正确的图片格式!')
  }
  const isLt2M = file.size / 1024 / 1024 < 1
  if (!isLt2M) {
    message.error('图片大小不能超过1MB!')
  }
  return isJpgOrPng && isLt2M
}
</script>

<style lang="less" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.imgStyle {
  width: 100%;
  object-fit: contain;
}
</style>
